﻿using AiBLSmartEdu.Module.CreditAnalysis.API.DTOs;
using Domain.Entities;
using Domain;
using AutoMapper;
using FrameworkCore.DI;
using FrameworkCore.Events;
using FrameworkCore.Extensions;
using FrameworkCore.Helpers;
using FrameworkCore.Interfaces;
using FrameworkCore.Models;
using FrameworkCore.Repositories;

namespace AiBLSmartEdu.Module.CreditAnalysis.API.Services;

#nullable disable

/// <summary>
/// 文档服务
/// </summary>
public class DocumentServices : IScopedDependency
{
    private readonly IRepository<Document> _documentRepository;
    private readonly IMapper _mapper;
    private readonly ICurrentUserService _currentUserService;
    private readonly IEventPublisher _eventPublisher;

    public DocumentServices(
        IRepository<Document> documentRepository,
        IMapper mapper,
        ICurrentUserService currentUserService,
        IEventPublisher eventPublisher)
    {
        _documentRepository = documentRepository;
        _mapper = mapper;
        _currentUserService = currentUserService;
        _eventPublisher = eventPublisher;
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="filter">分页输入模型</param>
    /// <returns></returns>
    public async Task<PageResult<DocumentOutputModel>> PageAsync(DocumentPaginationFilter filter)
    {
        return (await _documentRepository.GetOrderedQueryable(query =>
        {
            return query.WhereIf(!filter.Title.IsNullOrWhiteSpace(), x => x.Title.Contains(filter.Title))
                        .WhereIf(!filter.Path.IsNullOrWhiteSpace(), x => x.Path.Contains(filter.Path))
                        .WhereIf(filter.Status.HasValue, x => x.Status == filter.Status);


        }, filter).ProjectToPaginatedDataAsync<Document, DocumentOutputModel>(
            filter.PageNumber,
            filter.PageSize,
            _mapper.ConfigurationProvider
        )).ToPageList();
    }

    /// <summary>
    /// 创建
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task CreateAsync(DocumentCreateInputModel input)
    {
        var model = _mapper.Map<Document>(input);
        model.Status = JobStatus.NotStart;
        await _documentRepository.InsertAsync(model);
    }


    /// <summary>
    /// 获取一条数据
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<Document> GetByIdAsync(long id) 
    {
       return await _documentRepository.GetByIdAsync(id);
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="input">输入模型</param>
    /// <returns></returns>
    public async Task UpdateAsync(DocumentUpdateInputModel input)
    {
        var document = await _documentRepository.GetByIdAsync(input.Id);
        ExceptionHelper.ThrowIfNull(document, "文档不存在");

        await _documentRepository.UpdateAsync(x =>
            x.SetProperty(p => p.Title, p => input.Title)
             .SetProperty(p => p.Path, p => input.Path), w => w.Id == input.Id);
    }

    /// <summary>
    /// 修改内容摘要
    /// </summary>
    /// <param name="id"></param>
    /// <param name="content"></param>
    /// <param name="summary"></param>
    /// <returns></returns>
    public async Task UpdatContentSummaryAsync(long id,string content,string summary)
    {
        await _documentRepository.UpdateAsync(x => x
            .SetProperty(p => p.Content, p => content)
            .SetProperty(p => p.Summary, p => summary)
            .SetProperty(p => p.Status, p => JobStatus.Completed), w => w.Id == id);
    }

    /// <summary>
    /// 修改状态
    /// </summary>
    /// <param name="id"></param>
    /// <param name="status"></param>
    /// <returns></returns>
    public async Task UpdatStatusAsync(long id, JobStatus status)
    {
        await _documentRepository.UpdateAsync(x => x
            .SetProperty(p => p.Status, p => status), w => w.Id == id);
    }

    /// <summary>
    /// 查询
    /// </summary>
    /// <param name="func">查询表达式</param>
    /// <returns></returns>
    public async Task<IList<Document>> QueryAsync(Func<IQueryable<Document>, IQueryable<Document>> func)
    {
       return  await _documentRepository.GetAllAsync(func);
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="ids">唯一标识，多个使用英文状态下的逗号（,）隔开</param>
    /// <returns></returns>
    public async Task DeleteAsync(string ids)
    {
        ExceptionHelper.ThrowIfNull(ids, "删除的唯一标识不能为空");

        List<long> idsToDelste = ids
            .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)  // 分割字符串
            .Select(id =>
            {
                if (long.TryParse(id.Trim(), out long result))
                {
                    return result;
                }
                else
                {
                    ExceptionHelper.ThrowIfTrue(true, "无效的标识");
                    return 0;
                }
            }).ToList();

        await _documentRepository.DeleteAsync(x => idsToDelste.Contains(x.Id));
    }
}
